//
//  SMAlertViewController.m
//  Demo
//
//  Created by btcc on 2021/6/29.
//

#define ConstScreenWidth                ([UIScreen mainScreen].bounds.size.width)
#define ConstScreenHeight               ([UIScreen mainScreen].bounds.size.height)

#import "SMAlertViewController.h"
#import <Masonry/Masonry.h>

typedef void(^CompleteBlock)(NSInteger currentIndex);
@interface SMAlertViewController ()

@property (nonatomic, strong) NSArray<NSString *> *actionTitles; // 功能能按钮
@property (nonatomic, strong) NSMutableArray<UIButton *> *itemButtonArray; // 按钮数组
@property (nonatomic, strong) UIView *alertView; // 弹出框背景view
@property (nonatomic, strong) UILabel *titleLabel; // 标题
@property (nonatomic, strong) UILabel *contentLabel; // 内容
@property (nonatomic, strong) UIView *lineView; // 分割线
@property (nonatomic, strong) UIView *vLineView; // 分割线竖线
@property (nonatomic, strong) UIButton *tempButton; // 临时button
@property (nonatomic,   copy) CompleteBlock completeBlock; // 完成回调
@end

@implementation SMAlertViewController

+ (instancetype)alertViewWithTitle:(NSString *)title message:(NSString *)message actionsTitle:(NSArray<NSString *> *)actionTitles completeHandle:(void(^)(NSInteger currentIndex))handle {
    SMAlertViewController *alertController = [[SMAlertViewController alloc] init];
    alertController.actionTitles = actionTitles;
    alertController.titleLabel.text = title;
    alertController.contentLabel.text = message;
    alertController.completeBlock = handle;
    return alertController;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationCurrentContext;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        self.view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.4];
        [self createUI];
    }
    return self;
}

#pragma mark -------------------- lazy --------------------

- (NSMutableArray<UIButton *> *)itemButtonArray {
    if (!_itemButtonArray) {
        _itemButtonArray = [NSMutableArray array];
    }
    return _itemButtonArray;
}

#pragma mark -------------------- setter --------------------

- (void)setActionTitles:(NSArray<NSString *> *)actionTitles {
    _actionTitles = actionTitles;
    if (actionTitles.count == 0) {
        [self.alertView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.contentLabel.mas_bottom).mas_offset(15);
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self showAnimation];
        });
        return;
    } else {
        [actionTitles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            self.tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.tempButton setTitle:obj forState:UIControlStateNormal];
            [self.tempButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
            if ([obj isEqualToString:@"取消"]) {
                [self.tempButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            } else {
                [self.tempButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
            self.tempButton.tag = idx;
            [self.alertView addSubview:self.tempButton];
            [self.itemButtonArray addObject:self.tempButton];
        }];
        
        [self.alertView addSubview:self.lineView];
        [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.alertView.mas_left);
            make.right.mas_equalTo(self.alertView.mas_right);
            make.top.mas_equalTo(self.contentLabel.mas_bottom).mas_offset(15);
            make.height.mas_equalTo(1);
        }];
        
        if (self.itemButtonArray.count == 1) {
            [self.itemButtonArray mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.lineView.mas_bottom).mas_offset(5);
                make.height.mas_equalTo(40);
                make.right.mas_equalTo(self.alertView.mas_right);
                make.left.mas_equalTo(self.alertView.mas_left);
            }];
        } else {
            [self.itemButtonArray mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:5 leadSpacing:5 tailSpacing:5];

            [self.itemButtonArray mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.lineView.mas_bottom).mas_offset(5);
                make.height.mas_equalTo(40);
            }];
            
            [self.alertView addSubview:self.vLineView];
            
            [self.vLineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.alertView.mas_centerX);
                make.top.mas_equalTo(self.lineView.mas_bottom).mas_offset(10);
                make.bottom.mas_equalTo(self.alertView.mas_bottom).mas_offset(-10);
                make.width.mas_equalTo(1);
            }];
        }
    }
    
    [self.alertView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.tempButton.mas_bottom).mas_offset(5);
    }];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showAnimation];
    });
}

#pragma mark -------------------- fun --------------------

- (void)clickButton:(UIButton *)sender {
    if (self.completeBlock) {
        [self dismissViewControllerAnimated:YES completion:^{
            self.completeBlock(sender.tag);
        }];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (touches.anyObject.view == self.view) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark -------------------- UI --------------------

- (void)createUI {
    [self.view addSubview:self.alertView];
    [self.alertView addSubview:self.titleLabel];
    [self.alertView addSubview:self.contentLabel];
    
    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.centerY.mas_equalTo(self.view.mas_centerY);
        make.width.mas_equalTo(ConstScreenWidth - 50);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.alertView.mas_centerX);
        make.top.mas_equalTo(self.alertView.mas_top).mas_offset(15);
    }];
    
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.alertView.mas_left).mas_offset(15);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).mas_offset(15);
        make.right.mas_equalTo(self.alertView.mas_right).mas_offset(-15);
    }];
}

- (void)showAnimation {
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    basicAnimation.fromValue = @1;
    basicAnimation.toValue = @1.1;
    basicAnimation.repeatCount = 1;
    basicAnimation.duration = 0.1;
    basicAnimation.removedOnCompletion = YES;
    basicAnimation.autoreverses = YES;
    [self.alertView.layer addAnimation:basicAnimation forKey:@"alert"];
}

#pragma mark -------------------- lazy --------------------

- (UIView *)alertView {
    if (!_alertView) {
        _alertView = [[UIView alloc] init];
        _alertView.backgroundColor = [UIColor whiteColor];
        _alertView.layer.cornerRadius = 8;
    }
    return _alertView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
    }
    return _titleLabel;
}

- (UILabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.numberOfLines = 0;
    }
    return _contentLabel;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3];
    }
    return _lineView;
}

- (UIView *)vLineView {
    if (!_vLineView) {
        _vLineView = [[UIView alloc] init];
        _vLineView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3];
    }
    return _vLineView;
}

@end
